<template>
  <div>
    <!-- 输入栏和按钮 -->
    <div style=" line-height: 40px;margin-bottom: 4px;height: 40px;">
      <el-input style="width: 200px; float: left;margin-left: 5px;" placeholder="请输入用户" v-model.trim="userNameKey"
        @keyup.enter.native="loadUsers(); messageAlert()" suffix-icon="el-icon-search" maxlength="20">provinceKey
      </el-input>
      <el-input style="width: 200px; float: left;margin-left: 5px;" placeholder="请输入省份" v-model.trim="provinceKey"
        @keyup.enter.native="loadUsers(); messageAlert()" suffix-icon="el-icon-message" type="email" maxlength="20">
      </el-input>
      <el-input style="width: 200px; float: left;margin-left: 5px;" placeholder="请输入城市" v-model.trim="cityKey"
        @keyup.enter.native="loadUsers(); messageAlert()" suffix-icon="el-icon-position" maxlength="50">
      </el-input>

      <!-- 一系列按钮 -->
      <el-button type="primary" style="float: left; margin-left: 5px;" @click="loadUsers(); messageAlert()">搜索
      </el-button>
      <el-button type="warning" style="float: left; margin-left: 7px;"
        @click="userNameKey='';cityKey='';provinceKey=''">重置
      </el-button>
      <!-- <el-button style="float: right; margin-left: 20px;" type="danger" @click="batchDeleteUsers()">批量删除<i class="el-icon-delete"
                        style="padding-left: 5px;"></i></el-button> -->
      <el-popconfirm title="确定删除该用户吗？" icon-color="red" @confirm="batchDeleteUsers"
        style="float: right;  margin-left: 15px; margin-top:-2px; ">
        <el-button slot="reference" type="danger">批量删除</el-button>
      </el-popconfirm>

      <!-- :on-success="importExcel" -->
      <!-- <el-upload action="http://localhost:9090/user/importExcel" :show-file-list="false" accept="xlsx"
                style="display: inline-block;float: right;"> -->
      <!-- <el-button :disabled="1===1" style="float: right; margin-left: 20px;" type="success">导入<i
          class="el-icon-folder-add" style="padding-left: 5px;"></i></el-button> -->
      <!-- </el-upload> -->

      <!-- @click="exportExcel()" -->
      <el-button style="float: right; margin-left: 20px;" type="info" @click="exportExcel()">导出<i class="el-icon-bottom"
          style="padding-left: 5px;"></i></el-button>

      <!--  -->
      <!--  -->
      <el-button style="float: right; margin-left: 40px; " type="primary"
        @click="dialogFormVisible = true; form.flag = '0'">
        新增<i class="el-icon-circle-plus-outline" style="padding-left: 5px;"></i></el-button>
      <!--点击新增跳出来的表单被修改按钮也使用  -->
      <el-dialog title="用户信息" :visible.sync="dialogFormVisible" style="margin-top: -110px;">
        <el-form :model="form" style="margin-left: -60px;">
          <el-form-item label="用户名" :label-width="formLabelWidth" required>
            <el-input v-model="form.username" autocomplete="off" maxlength="32" style="width: 500px; float: left;"><i
                slot="prefix" class="el-icon-user-solid"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" required>
            <el-input v-model="form.password" type="password" autocomplete="off" maxlength="20"
              style="width: 500px; float: left;"><i slot="prefix" class="el-icon-user-solid"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="权限" :label-width="formLabelWidth" required>
            <el-select clearable v-model="form.status" placeholder="请选择角色" style="width: 500px;">
              <el-option v-for="item in roles" :key="item.name" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="昵称" :label-width="formLabelWidth" required>
            <el-input v-model="form.nickName" autocomplete="off" maxlength="32" style="width: 500px; float: left;"> <i
                slot="prefix" class="el-icon-user"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth" required>
            <!-- <el-input v-model="form.gender" autocomplete="off" maxlength="50" style="width: 500px; float: left;"> <i
                slot="prefix" class="el-icon-male"></i>
            </el-input> -->
            <el-select v-model="genderForm" placeholder="请选择" style="width: 500px;">
              <el-option v-for="item in ['男','女']" :key="item" :label="item" :value="item"><i slot="prefix"
                  class="el-icon-man"></i>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" required type="email">
            <el-input v-model="form.email" autocomplete="off" maxlength="20" style="width: 500px; float: left;"> <i
                slot="prefix" class="el-icon-message"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="电话" :label-width="formLabelWidth" required>
            <el-input v-model="form.phone" autocomplete="off" maxlength="11" style="width: 500px; float: left;"> <i
                slot="prefix" class="el-icon-phone"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="省份" :label-width="formLabelWidth" required>
            <el-input v-model="form.province" autocomplete="off" maxlength="50" style="width: 500px; float: left;"> <i
                slot="prefix" class="el-icon-position"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="城市" :label-width="formLabelWidth" required>
            <el-input v-model="form.city" autocomplete="off" maxlength="50" style="width: 500px; float: left;"> <i
                slot="prefix" class="el-icon-position"></i>
            </el-input>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" style="float: left;" @click="judgeUserName(form.username)">测试用户名是否存在</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false;
                    form.flag === '0' ? submitForm() : updateUser()">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <div style="height: 90%;padding-top: 0px;padding-bottom: 5px;margin-top: 6px;">
      <!-- 表格 -->
      <el-table :data="tableData" border stripe :header-cell-class-name="headerStyle"
        @selection-change="handSelectChange" :row-style="{height: '0px'}" :cell-style="{padding: '0px'}">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="nickName" label="昵称"></el-table-column>
        <el-table-column prop="gender" label="性别" :formatter="sexFormat" width="50"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="phone" label="电话" width="160"></el-table-column>
        <el-table-column prop="province" label="省份" width="140"></el-table-column>
        <el-table-column prop="city" label="城市" width="140"></el-table-column>
        <el-table-column prop="status" label="权限" :formatter="statusFormat" width="80"></el-table-column>

        <el-table-column label="操作" width="120">

          <!--slot-scope="scope"一个添加条件 叫做插槽;  -->
          <template slot-scope="scope">
            <el-button type="text" @click="dialogFormVisible = true; fillUserData(scope.row)">编辑
            </el-button>
            <!-- 删除按钮，弹出框提醒 Popconfirm 气泡确认框，Popover 弹出框不成功-->
            <el-popconfirm title="确定删除该用户吗？" icon-color="red" @confirm="deleteUser(scope.row.id)">
              <el-button slot="reference" type="text">删除</el-button>
            </el-popconfirm>
          </template>

        </el-table-column>
      </el-table>
    </div>

    <div class="block" style="padding: 5px;margin-bottom: -10px;padding-left: 380px;">
      <span class="demonstration"></span>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
        :page-sizes="[10, 12, 16]" :page-size="12" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>

</template>

<script>
  export default {
    name: 'User',
    data() {
      return {
        tableData: [], //页面数据
        total: 0, //页面大小
        pageNum: 1, //页码
        pageSize: 12, //页大小

        genderForm: '',

        //关键字查询
        userNameKey: '',
        cityKey: '',
        provinceKey: '',
        //表格加载图片
        loading: true,

        tableRowClassName: 'tableRowClassName',

        // 弹出框提醒
        visible: false,

        // 新增表单信息
        dialogFormVisible: false,
        form: {
          flag: '0', //如果是0点击表单就是添加方法,如果是1就是修改方法
          username: '',
          nickName: '',
          gender: '',
          phone: '',
          email: '',
          city: '',
          status: '',
          province: '',
          password: ''
        },
        formLabelWidth: '200px',

        // 多选情况
        multipleSelection: [],

        //权限情况
        roles: [],
      }
    },
    methods: {
      sexFormat(row, column) {
        if (row.gender === null) {
          return "未知";
        }
        if (row.gender === '1') {
          return "男"
        } else if (row.gender === '2') {
          return "女"
        } else {
          return "未知"
        }
      },
      //是否多服务数据处理
      statusFormat(row, column) {
        if (row.status === 0) {
          return "超管"
        } else if (row.status === 1) {
          return "管理员"
        } else {
          return "用户"
        }
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.loadUsers();
      },
      handleCurrentChange(val) {
        this.pageNum = val;
        this.loadUsers();
      },
      headerStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        return 'tableStyle'
      },
      //获得后台users数据
      loadUsers() {
        // 获得数据之前加载加载页面
        const that = this;
        that.loading = true;
        this.$axios.get('/user/pageUsers', {
            params: {
              pageNum: that.pageNum,
              pageSize: that.pageSize,
              username: that.userNameKey,
              city: that.cityKey,
              province: that.provinceKey,
            }
          })
          .then(function (response) {
            //获得数据之后取消加载页面 
            that.loading = false;
            that.tableData = response.data.records
            that.total = response.data.total;
          })
          .catch(function (error) {
            console.log(error);
          })

        this.$axios.get('/role/roles')
          .then(function (response) {
            that.roles = response.data;
          })
          .catch(function (error) {
            console.log(error);
          })
      },
      // 消息提醒方法
      messageAlert() {
        this.$message({
          message: '查询成功！',
          type: 'success',
          duration: 1600
        });
      },
      messageAlert2() {
        this.$message({
          message: '提交成功',
          type: 'success',
          duration: 1600
        });
      },
      messageAlert3() {
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 1600
        });
      },

      //多选处理
      handSelectChange(val) {
        // 把选择的数字赋值data
        this.multipleSelection = val;
      },

      // 批量删除处理
      batchDeleteUsers() {
        let ids = this.multipleSelection.map(v => v.id);
        const that = this;
        that.loading = true;
        // delet只可以传递一个值，不可以传递对象数组
        this.$axios.post('/user/batchDeleteUsers', {
            ids: ids
          })
          .then(function (response) {
            that.loadUsers();
            that.messageAlert3();
          })
          .catch(function (error) {
            console.log(error);
          })
          .then(function () {
            // always executed
          });
      },
      //提交表单
      submitForm() {
        const that = this;
        that.loading = true;
        this.form.id = null;
        this.$axios.post('/user/save',
            // username: that.form.username,
            // nickName: that.form.nickName,
            // gender: that.form.gender,
            // phone: that.form.phone,
            // email: that.form.email,
            // city: that.form.city,
            // status: that.form.status,
            // province: that.form.province,
            that.form)
          .then(function (response) {
            if (response.data === false) {
              that.$message.error("添加错误或用户名重复");
              return;
            }
            //重新加载数据
            that.loadUsers();
            that.messageAlert2();
            // 清除数据
            that.form.username = '';
            that.form.nickName = '';
            that.form.gender = '';
            that.form.phone = '';
            that.form.email = '';
            that.form.city = '';
            that.form.status = '';
            that.form.province = '';
            that.genderForm = '';
            that.password = '';
          })
          .catch(function (error) {
            console.log(error);
          })
          .then(function () {
            // always executed
          });
      },

      // 删除用户
      deleteUser(id) {
        // 获得数据之前加载加载页面
        const that = this;
        that.loading = true;
        this.$axios.delete('/user/deleteUser', {
            params: {
              id: id
            }
          })
          .then(function (response) {
            that.loadUsers();
            that.messageAlert3();
          })
          .catch(function (error) {
            console.log(error);
          })
          .then(function () {
            // always executed
          });
      },

      fillUserData(user) {
        this.form.username = user.username;
        this.form.nickName = user.nickName;
        this.form.email = user.email;
        this.form.phone = user.phone;
        this.form.city = user.city;
        this.form.province = user.province;
        this.form.password = user.password;
        this.form.flag = '1'; //提交表单为修改操作
        this.form.id = user.id;
        if (user.gender === '1') {
          this.genderForm = '男';
        } else if (user.gender === '2') {
          this.genderForm = '女';
        } else {
          this.genderForm = '';
        }
        this.form.status = user.status;
      },
      updateUser() {
        const that = this;
        that.loading = true;
        this.$axios.post('/user/update', {
            userName: that.form.userName,
            nickName: that.form.nickName,
            gender: that.form.gender,
            phone: that.form.phone,
            city: that.form.city,
            province: that.form.province,
            email: that.form.email,
            id: that.form.id,
            status: that.form.status,
            password: that.form.password,
          })
          .then(function (response) {
            //重新加载数据
            that.loadUsers();
            that.$message({
              message: '修改成功',
              type: 'success',
              duration: 1600
            });
            // 清除数据
            that.form.username = '';
            that.form.nickName = '';
            that.form.city = '';
            that.form.province = '';
            that.form.nickName = '';
            that.form.phone = '';
            that.form.email = '';
            that.form.email = '';
            that.form.status = '';
            that.genderForm = '';
            that.form.password = '';
            // localStorage.setItem("user", JSON.stringify(this.user));

          })
          .catch(function (error) {
            console.log(error);
          })
          .then(function () {
            // always executed
          });
      },

      exportExcel() {
        window.open("http://127.0.0.1:9090/user/exportExcel");
      },

      // importExcel() {
      //   this.$message.success("导入成功");
      //   this.loadUsers();
      // }
      judgeUserName(username) {
        const that = this;
        that.loading = true;
        if (username === '') {
          this.$message.error("请输入用户名");
          return;
        }
        this.$axios.get('/user/judgeUserName', {
            params: {
              username: username
            }
          })
          .then(function (response) {
            if (response.data == true) {
              that.$message.success("用户名可用");
            } else {
              that.$message.error("用户名已存在");
            }
          })
          .catch(function (error) {
            console.log(error);
          })
      }
    },

    watch: {
      genderForm(newName, oldName) {
        if (newName === '男') {
          this.form.gender = 1;
        } else if (newName === '女') {
          this.form.gender = 2;
        } else {
          this.form.gender = 0;
        }
      }
    },

    created() {
      //以下代码也可以封装在函数中，在其他地方调用

      // 然而问题是出来了this.tableData因为用了 function 函数 的原因，
      // 在函数里面，this是指向函数本身，已经不是外部的默认this了
      this.loadUsers();
    },
  }

</script>

<style>
  .tableStyle {
    background-color: rgb(236, 236, 236) !important;
    color: rgb(0, 0, 0);
    font-weight: 500;
    font-size: medium;
  }

</style>
